#qpy:pygame


import sys
f = open('log.py', 'w')
sys.stdout = f
sys.stderr = f


import pygame as pg
import random

class V2(object):
  def __init__(self, x, y=None):
    if y is None:
      x, y = x
    self.x = x
    self.y = y
  
  def __repr__(self):
    return repr([self.x, self.y])
  
  def __add__(a, b):
    return V2(a.x + b.x, a.y + b.y)
  
  def __sub__(a, b):
    return V2(a.x - b.x, a.y - b.y)
    
  def __mul__(self, k):
    return V2(self.x * k, self.y * k)

  def __rmul__(self, k):
    return V2(self.x * k, self.y * k)

  def __div__(self, k):
    return V2(self.x / k, self.y / k)
  
  def t(self):
    return (self.x, self.y)
  
  def dot(a, b):
    return a.x * b.x + a.y * b.y
    
  def length(self):
    return (self.x ** 2 + self.y ** 2) ** 0.5
  
  def norm(self):
    return self / self.length()
    
def fenjie(v, dir1):
  dir1 = dir1.norm()
  dir2 = V2(-dir1.y, dir1.x)
  return (v.dot(dir1), v.dot(dir2))

def hecheng(t, dir1):
  dir1 = dir1.norm()
  dir2 = V2(-dir1.y, dir1.x)
  x, y = t
  return x * dir1 + y * dir2

def rc():
  r = random.randint
  return (r(0, 255), r(0, 255), r(0,255))
  
class Circle(object):
  def __init__(self, p0, v0):
    self.p = p0
    self.v = v0
    self.image = pg.Surface((100,100), flags=pg.SRCALPHA)
    pg.draw.circle(self.image, rc(), (50, 50), 50)
    
    self.record =[]
    
  @property
  def rect(self):
    return self.image.get_rect(center=self.p.t())
    
  def move(self, dt):
    self.p += self.v * dt
   
  def touch(self, obj):
    if self is obj:
      pass
    elif self in obj.record:
      pass
    else:
      if (self.p - obj.p).length() <= 100:
        self.record.append(obj)
        dir = self.p - obj.p
        v1, v2 = fenjie(self.v, dir)
        v3, v4 = fenjie(obj.v, dir)
        self.v = hecheng((v3, v2), dir)
        obj.v = hecheng((v1, v4), dir)
    
    rect = self.rect
    if rect.bottom > size[1]:
      if self.v.y >0:
        self.v.y *= -1
    if rect.top < 0:
      if self.v.y < 0:
        self.v.y *= -1
    if rect.left < 0:
      if self.v.x <0:
        self.v.x *= -1
    if rect.right > size[0]:
      if self.v.x >0:
        self.v.x *= -1

  def draw(self):
    screen.blit(self.image, self.rect)

obj_list = []
temp =[None]

pg.init()
screen = pg.display.set_mode((10,10))
size = screen.get_size()
clock = pg.time.Clock()
while True:
  dt = clock.tick(60) / 1000.0
  for e in pg.event.get():
    if e.type == pg.MOUSEBUTTONUP:
      if V2(e.pos) != temp[0]:
        p = V2(e.pos)
        v = (V2(e.pos) - temp[0]).norm()
        v = v * 1000
        obj_list.append(Circle(p, v))
    elif e.type == pg.MOUSEBUTTONDOWN:
      temp[0] = V2(e.pos)
  
  for c in obj_list:
    c.move(dt)
  for c in obj_list:
    c.record = []
  for i in obj_list:
    for j in obj_list:
      i.touch(j)
  
  screen.fill((255, 255, 255))
  for c in obj_list:
    c.draw()
  pg.display.update()
        	
      

